package com.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Yadasu
 * @Description Http相关的工具类
 * @Date 2020/10/7 11:38
 * @Version 1.0
 */
public class HttpUtils {
    private HttpUtils() {

    }

    /**
     * @Author Yadasu
     * @Description TODO 将data转换为Json字符串发送给前端
     * @Date 2020/10/7 11:39
     * @Version 1.0
     */
    public static void writeJson(HttpServletResponse res, Object data) {
        res.setContentType("application/json;charset=utf-8");
        try (PrintWriter pw = res.getWriter()) {
            pw.write(new ObjectMapper().writeValueAsString(data));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author Yadasu
     * @Description TODO 将data转换为Json字符串发送给前端，同时设置状态码
     * @Date 2020/10/7 11:39
     * @Version 1.0
     */
    public static void writeJson(HttpServletResponse res, Object data, int code) {
        res.setStatus(code);
        writeJson(res, data);
    }
}
